package gee

import (
	"encoding/json"
	"net/http"
)

type Context struct {
	Resp http.ResponseWriter
	Req  *http.Request

	Path   string
	Method string
	Status int
}

type H map[string]interface{}

func NewContext(rw http.ResponseWriter, r *http.Request) *Context {

	c := &Context{
		Resp:   rw,
		Req:    r,
		Path:   r.URL.Path,
		Method: r.Method,
		Status: 200,
	}
	return c
}

// ============ Request ============ //
func (c *Context) Get(name string) string {

	return c.Req.URL.Query().Get(name)
}

func (c *Context) Post(name string) string {

	return c.Req.PostFormValue(name)
}

func (c *Context) Header(name string) string {

	return c.Req.Header.Get(name)
}

// ============ Response ============ //
func (c *Context) SetHeader(key string, value string) {

	c.Resp.Header().Set(key, value)
}

func (c *Context) SetStatusCode(code int) {
	c.Status = code
	c.Resp.WriteHeader(code)
}

func (c *Context) HTML(html string) {

	c.SetHeader("Content-Type", "text/plain")
	c.Resp.Write([]byte(html))
}

func (c *Context) JSON(data interface{}) {

	encoder := json.NewEncoder(c.Resp)
	if err := encoder.Encode(data); err != nil {
		http.Error(c.Resp, err.Error(), http.StatusInternalServerError)
	}
	c.SetHeader("Content-Type", "application/json")
}

func (c *Context) Text(text string) {

	c.SetHeader("Content-Type", "text/plain")
	c.Resp.Write([]byte(text))
}

func (c *Context) Data(data []byte) {

	c.Resp.Write(data)
}
